package com.soft.mainsite.component.beetl.tag.cms;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.soft.mainsite.common.constant.CmsConst;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.exception.SystemException;
import com.soft.mainsite.common.utils.CmsUtil;
import com.soft.mainsite.module.publishlog.service.PublishLogService;
import com.soft.mainsite.module.web.cms.service.CategoryService;
import com.soft.mainsite.module.web.cms.service.ContentService;
import com.soft.mainsite.module.web.cms.service.SiteService;
import com.soft.mainsite.mybatis.model.TCmsCategory;
import com.soft.mainsite.mybatis.model.TCmsSite;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.soft.mainsite.common.constant.CmsConst.MAIN_SITE_ID;

/**
 * Description:内容列表标签
 *
 * @author Jin
 * @create 2017-05-26
 **/
@Slf4j
@Service
@Scope("prototype")
public class FlagshipShopListTag extends GeneralVarTagBinding {

    @Autowired
    private ContentService contentService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private PublishLogService publishLogService;

    @Autowired
    private CategoryService categoryService;

    @Value("${system.site.subfix}")
    private String siteSubfix;

    @Value("${system.site.prefix}")
    private String sitePrefix;


    /**
     * 文章列表标签
     * <p>
     * siteId:站点id
     * categoryId:分类编号
     * hasChild：是否包含子栏目内容
     * isHot：热门
     * titleLen:标题长度
     * target:是否新窗口打开
     * orderBy:排序
     * size:调用条数
     * recommend:是否推荐 ：0为不推荐，1为推荐
     */
    @Override
    public void render() {
        if (CmsUtil.isNullOrEmpty(this.args[1])) {
            throw new SystemException("标签参数不能为空！");
        }
        String whereParam = Convert.toStr(this.getAttributeValue("whereParam"));
        String valueParam = Convert.toStr(this.getAttributeValue("valueParam"));

        Integer isPub = CmsUtil.isNullOrEmpty(this.getAttributeValue("isPub")) ? 0 : Convert.toInt(this.getAttributeValue("isPub"));
        boolean isStatic = Convert.toBool(this.getAttributeValue("isStatic"));
        Integer titleLen = Integer.parseInt((String) this.getAttributeValue("titleLen"));
        Integer descriptionLen = CmsUtil.isNullOrEmpty(this.getAttributeValue("descriptionLen")) ? 0 : Convert.toInt(this.getAttributeValue("descriptionLen"));
        Integer siteId = Convert.toInt(this.getAttributeValue("siteId"));
        String siteType = Convert.toStr(this.getAttributeValue("siteType"));
        Long categoryId = Convert.toLong(this.getAttributeValue("categoryId"));
        Integer hasChild = Convert.toInt(this.getAttributeValue("hasChild"));
        Integer isPic = Integer.parseInt(CmsUtil.isNullOrEmpty(this.getAttributeValue("isPic")) ? "3" : (String) this.getAttributeValue("isPic"));
        Integer isRecommend = Integer.parseInt(CmsUtil.isNullOrEmpty(this.getAttributeValue("isRecommend")) ? "0" : (String) this.getAttributeValue("isRecommend"));
        Integer orderBy = Integer.parseInt((String) this.getAttributeValue("orderBy"));
        Integer pageNumber = Integer.parseInt((CmsUtil.isNullOrEmpty(this.getAttributeValue("pageNumber")) ? "1" : (String) this.getAttributeValue("pageNumber")));
        Integer pageSize = Integer.parseInt((String) this.getAttributeValue("size"));
        Integer pubPageSize = Convert.toInt(this.getAttributeValue("pubSize"));
        // 排序字段
        Integer sortNum = Convert.toInt(this.getAttributeValue("sortNum"));

        if (CmsUtil.isNullOrEmpty(this.getAttributeValue(CmsConst.PARAM_PUBSIZE))) {
            pubPageSize = pageSize;
        }

        if (CmsConst.MAIN_SITE_TYPE.equals(siteType)) {
            siteType = null;
        }

        Integer isHot = Integer.parseInt((String) this.getAttributeValue("isHot"));

        if (CmsConst.IS_PUB.equals(isPub)) {
            siteId = MAIN_SITE_ID;
            pageSize = pubPageSize;
        }

        PageInfo<Map> pageInfo = contentService.findContentListBySiteIdAndCategoryId(siteId, siteType, categoryId, orderBy, pageNumber, pageSize, hasChild, isHot, isPic, isRecommend, whereParam, valueParam, sortNum);
        long total = pageInfo.getTotal();
        if (CmsUtil.isNullOrEmpty(pageInfo.getList())) {
            siteId = MAIN_SITE_ID;
            pageInfo = contentService.findContentListBySiteIdAndCategoryId(siteId, siteType, categoryId, orderBy, pageNumber, pageSize, hasChild, isHot, isPic, isRecommend, whereParam, valueParam, sortNum);
        }
        total = pageInfo.getTotal();
        if (CmsUtil.isNullOrEmpty(pageInfo.getList())) {
            return;
        }
        try {
            this.wrapRender(pageInfo.getList(), titleLen, siteId, total, isStatic, descriptionLen);
        } catch (Exception e) {
            log.error("内容列表标签渲染失败,栏目id：{}", categoryId, e);
            publishLogService.save(siteId, categoryId, "", "内容列表标签渲染失败,栏目id:" + categoryId);
            throw new CmsException("内容列表标签渲染失败，" + "栏目id:" + categoryId);
        }
    }

    private void wrapRender(List<Map> contentList, int titleLen, int siteId, long total, boolean isStatic, int descriptionLen) {
        HttpServletRequest request = (HttpServletRequest) ctx.getGlobal("request");
        String staticHtmlPath = ctx.getGlobal("staticHtmlPath") == null ? "" : (String) ctx.getGlobal("staticHtmlPath");
        int i = 1;
        for (Map content : contentList) {
            String title = content.get("title").toString();
            int length = title.length();
            if (length > titleLen) {
                content.put("title", title.substring(0, titleLen) + "...");
            }
            String description = "";
            if (content.containsKey("description")) {
                description = content.get("description").toString();
            }
            if (descriptionLen != 0 && description.length() > descriptionLen) {
                content.put("description", description.substring(0, descriptionLen) + "...");
            }
            if (content.get("url") == null || StrUtil.isBlank(content.get("url").toString())) {
                TCmsSite site = siteService.findById(siteId);

                if (CmsUtil.isNullOrEmpty(site)) {
                    throw new CmsException("站点不存在[siteId:" + siteId + "]");
                }
                TCmsCategory category = categoryService.findById(Long.parseLong(content.get("categoryId").toString()));
                if (CmsUtil.isNullOrEmpty(category)) {
                    throw new CmsException("栏目不存在[categoryId:" + category.getCategoryId() + "]");
                }
                String url = request.getContextPath() + staticHtmlPath + "/" + site.getSiteKey() + "/";
                url += category.getAlias() + "/" + content.get("contentId");

                //静态化时主站发布的公共栏目内容存放到common/content里面
                if (isStatic && category.getCommon() && MAIN_SITE_ID.equals(Convert.toInt(content.get("siteId")))) {
                    url = "/commonHtml/content/mobile/" + category.getAlias() + "/" + content.get("contentId");
                }

                content.put("url", url + siteSubfix);
            }
            content.put("index", i);
            content.put("count", total);
            this.binds(content);
            this.doBodyRender();
            i++;
        }

    }

}
